<?php
defined( '_VALID_MOS' ) or die( 'Restricted access' );
@session_start();
error_reporting(E_ALL ^E_NOTICE);
//error_reporting(0);
if (file_exists( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' ))
    include_once( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' );
else
    require_once( $mosConfig_absolute_path.'/components/com_jcs/languages/english.php' );

require_once( $mosConfig_absolute_path.'/administrator/components/com_jcs/jcs.functions.php');

if(!class_exists('JEConfig'))
    require_once( $mosConfig_absolute_path.
        '/administrator/components/com_jcs/joomlaequipment.config.php');
        
$update = $mosConfig_absolute_path.'/administrator/components/com_jcs/update.php';
if(file_exists($update)) include $update;

$task 	= mosGetParam( $_REQUEST, 'task', 'default' );
$option = mosGetParam( $_REQUEST, 'option', 'com_jcs');
$adwords = mosGetParam( $_REQUEST, 'adwords', 0);
if($adwords)
{
    echo jcsAdWordsCode($adwords);
}
//print_r($_POST);
//echo session_id();
global $database, $my;
global $mosConfig_live_site;

//echo $task;
switch ($task) {
	case 'pay':
     jcsProcessPay();
    break;
    
  case "registration":
    jcsSaveRegistration();
	case "register":
    jcsRegistration();
  	break;

	case 'addsubscription':
    jcsAddSubscription();
	case 'add':
  	jcsAddSubscriptionForm(mosGetParam( $_REQUEST, 'id', 0));
  break;		
  
  default:
		jcsViewSubscriptions();
  break;
}

function jcsRegistration()
{
    global $mainframe, $my;
    
    if($my->id)
    { 
       $mainframe->logout();
       mosRedirect('index.php?option=com_jcs&task=register');
    }
    include_once(dirname(__FILE__).'/view/register.php');
    //jcsAddSubscriptionForm(true);
    
}
function jcsProcessPay()
{
    global $_MAMBOTS,$mainframe, $my, $JCS_ORDER_COMPLETE, $JCS_ORDER_INCOMPLETE, $mosConfig_live_site;
    
    $order = $_MAMBOTS->trigger('onPayProsessFinish');
    //$my = $mainframe->getUser();
    //print_r($result); print_r($my); print_r($_SESSION);
    //print_r($_GET); print_r($_POST); session_id(); Exit;
    //print_r($order); return;
    foreach($order AS $key => $val)
    {
        if(@intval($val['id']) > 0)
        {
            if($val['pay'] == 'success')
            {
                jcsActivateSubscription($val, 1, $mosConfig_live_site.'/index.php?option=com_jcs&smsg='.urlencode($JCS_ORDER_COMPLETE));
                return;
            }
            else
            {
                jcsActivateSubscription($val, 0, $mosConfig_live_site.'/index.php?option=com_jcs&smsg='.urlencode($JCS_ORDER_INCOMPLETE));
                return;
            }
        }
    }
    // authorize net fix
    $id = $_SESSION['subscription'];
    unset($_SESSION['subscription']);
    if($id){
        $val['id'] = $id;
        jcsActivateSubscription($val, 0, $mosConfig_live_site.'/index.php?option=com_jcs&smsg='.urlencode($JCS_ORDER_INCOMPLETE));
    } 
}
function jcsActivateSubscription($id, $publish = 1, $url = 'index.php?option=com_jcs')
{
    global $database, $my, $JCS_SEE_ARTICLE;
    if(!$my->id) $my->id = mosGetParam( $_REQUEST, 'x_cus_id');
    //echo $my->id. $id.$publish;
    //return;
    jcsMakeSubscr($my->id, $id, $publish, $url);
}

function jcsAddSubscription()
{
    global $database, $my, $_MAMBOTS, $mosConfig_fromname,$mosConfig_sitename, 
    $JCS_ERROR_NOSABSCR, $JCS_ERROR_NOPAY, $JCS_ORDER_COMPLETE, $Itemid;
    
    $s = intval(mosGetParam( $_REQUEST, 'stype', false ));
    $p = mosGetParam( $_REQUEST, 'payprocessor', false );
    $coupon = mosGetParam( $_REQUEST, 'coupon', false );
    //$ca = mosGetParam( $_REQUEST, 'ca', false );
    
    $_SESSION['subscription'] = $s;
    $_SESSION['testsomething'] = session_id();

    $sql = "SELECT id, days, price, name FROM #__jcs_plans WHERE id = $s";
    $database->setQuery( $sql );
    $row = $database->loadObjectList();
    $row = $row[0];
    //$row->price = mosGetParam( $_REQUEST, 'price'.$s, 0 );
    //print_r($row);
    
    if($row->discount)
    {
    	$sql = "SELECT COUNT(*) AS total FROM #__jcs_user_subscr WHERE subscription_id = $s";
    	$database->setQuery( $sql );
    	$total = $database->loadResult();
    	if($total > 0)
    	{
    		$row->price = $row->price - (($row->price / 100) * $row->discount);
    	}
    }
    
    if(JEConfig::get('general.coupons'))
    { 
        $cpn = explode("\n", str_replace("\r","",JEConfig::get('general.coupons')));
        Foreach($cpn AS $cp)
        {
            $tmp = explode("+", $cp);
            $coupons[$tmp[0]] = $tmp[1];
        }
    }
    //print_r($coupons);
    //echo $coupon;
    if($coupon && (!in_array($coupon, array_flip($coupons))))
    {
        $_GET['smsg'] = JCS_ERROR_COUPON;
        return;
        //mosRedirect("index.php?option=com_jcs&amp;task=add&amp;Itemid={$Itemid}&amp;smsg=".JCS_ERROR_COUPON);
    } 
    if($coupon && (in_array($coupon, array_flip($coupons))))
    {
        $dev = $coupons[$coupon];
        $row->price = number_format($row->price - ($row->price * ($dev / 100)),2,'.','');
        //echo $row->price;
        //return;
    }
    
    //echo $row->price; exit();
    
    if($row->price <= 0)
    {
        $val['id'] = $s;
        $val['price'] = 0;
        $val['gateway'] = '.zeroprice';
        $val['gateway_id'] = time();
        jcsActivateSubscription($val, 1, 'index.php?option=com_jcs&smsg='.urlencode($JCS_ORDER_COMPLETE));
    }
    
    $params['params']['processor']= $p;
    //echo "ffffffffffffffffffffffffffffff".mosGetParam( $_REQUEST, 'price'.$s, false ); return;
    $params['params']['order_amount'] = $row->price;
    $params['params']['order_id']     = $s;
    $params['params']['order_title']  = $mosConfig_sitename.' :: '.$row->name;
    $params['params']['order_quantity'] = 1;
    
    $params['params']['item_number'] = $s;
    $params['params']['item_name'] = $mosConfig_sitename.' :: '.$row->name;

    $params['params']['tax_fixed'] = NULL;
    $params['params']['tax_procent'] = NULL;
    $params['params']['shipping_address'] = NULL;
    $params['params']['shipping_cost1'] = NULL;
    $params['params']['shipping_cost2'] = NULL;
    $params['params']['recurrence'] = 'N';
    $params['params']['recurrence_unit'] = NULL;
    $params['params']['recurrence_num']  = NULL;
    $params['params']['custom1']  = NULL;
    $params['params']['custom2']  = NULL;
    
    $_MAMBOTS->trigger('onPayProsessStart', $params);

}
function jcsAddSubscriptionForm($id = 0)
{
    global $database, $my, $mainframe, $mosConfig_live_site;
    
    
	  $sql = "SELECT p.id AS subs FROM #__jcs_plans AS p 
    LEFT JOIN #__jcs_user_subscr AS u ON u.subscription_id = p.id
    WHERE 1 
      AND u.user_id = $my->id 
   GROUP BY p.id
      ";
    $database->setQuery( $sql );
    $plans = $database->loadResultArray();
    //print_r($plans);
    if($id) $and = " AND p.id = '{$id}' "; Else $and = "";
    $sql = "
   SELECT p.*, c.name AS cname, c.description AS cdescr  FROM #__jcs_plans AS p
LEFT JOIN #__categories AS c ON c.id = p.catid
    WHERE 1 AND p.published = 1 
    and p.invisible = 0 
    {$and}
    ORDER BY c.ordering ASC, p.ordering ASC";
    $database->setQuery( $sql );
    $rows = $database->loadObjectList();
    
    $coupons = (boolean)JEConfig::get('general.coupons');
    $msg = urldecode($_GET['smsg']);
    
    if(!$my->id && (mosGetParam( $_REQUEST, 'hide_login', 0) != 1)) {
      include_once(dirname(__FILE__).'/view/login.php');
    	//return;
    }
    if(mosGetParam( $_REQUEST, 'hide_add', 0) != 1)
    include_once(dirname(__FILE__).'/view/add.php');
    
}
function jeMakePayProcessor($type='radio')
{
    global $database, $my, $JCS_ERROR_NOPAYPROC;
 
    $sql = "SELECT * FROM #__mambots WHERE element LIKE 'joomlaequipment.payprocessor.%' AND published = '1'";
    $database->setQuery( $sql );
    $rows = $database->loadObjectList();
    if(count($rows) == 0)
    {
        return $JCS_ERROR_NOPAYPROC;
    }
    $middle = '';
    foreach($rows as $row)
    {
        $value = strrchr($row->element, '.');
        ereg("[a-zA-z]* \[([0-9_a-zA-Z ]*)\]", $row->name, $reg);
        $name =str_replace("_", " ", $reg[1]);
        if(!$ch) {$check = ' checked="checked" '; $ch++;} else $check = '';
        switch($type)
        {
            case "select":
              $start = '<select name="payprocessor">';
              $middle .= "<option value={$value}>{$name}</option>";
              $end = '</select>';
              $hd = '<INPUT type="hidden" name="payprocessor" value="{$value}" />';
            break;

            case "radio":
              $start = '';
              $middle .= "<input align=\"absmiddle\" $check id={$value} type=\"radio\" name=\"payprocessor\" value={$value}> <label for=\"{$value}\">{$name}</label><br>";
              $end = '';
              $hd = '<INPUT type="hidden" name="payprocessor" value="'.$value.'" />';
            break;
        }
    }
    //echo count($rows);
    if(count($rows) == 1)
    {
        return JCS_PAY_WITH.$name.$hd;
    }
    return $start.$middle.$end;
}    
function jcsViewSubscriptions()
{
    
	  global $database, $mainframe, $my, $JCS_TITLE_SM, $JCS_NEW, $JCSOrderID, $JCSOrderAmount;
    if(!$my->id)
    {
        include_once(dirname(__FILE__).'/view/login.php');
        return;
    }
 
    $sql = "
    	SELECT 	u.id, u.published, u.price, u.access_limit, u.access_count, 
    			DATE_FORMAT(u.ctime, '%d, %b %Y') AS ctime, 
    			DATE_FORMAT(u.extime,'%d, %b %Y' ) AS extime, s.name, 
    			(TO_DAYS(u.extime) - TO_DAYS(NOW())) as days 
    	  FROM  #__jcs_user_subscr AS u 
     LEFT JOIN  #__jcs_plans AS s ON s.id = u.subscription_id  
	     WHERE  u.user_id = {$my->id} 
	       AND s.published = 1 
	  ORDER BY u.ctime DESC";
    //ho $sql;
    $database->setQuery( $sql );
    $rows = $database->loadObjectList();
    //print_r($rows);
    $msg = urldecode($_GET['smsg']);
    $sid = mosGetParam($_REQUEST, 'sid');
    $iid = mosGetParam($_REQUEST, 'iid');
    if($sid > 0)
    {
        $sql = "SELECT finish_msg FROM #__jcs_plans WHERE id = '{$sid}'";
        $database->setQuery( $sql );
        $finish = $database->loadResult();
    }
    /*
    $im_url = JEConfig::get('general.image_call');
    if($im_url && (substr($im_url, 0, 17) != 'http://mysite.com'))
    {
        $sql = "SELECT * FROM #__jcs_user_subscr WHERE id = '{$iid}'";
        $database->setQuery( $sql );
        $cs = $database->loadObjectList();
        $cs = $cs[0];
        $im_url = str_replace("[price]",    $cs->price, $im_url);
        $im_url = str_replace("[title]",    $cs->name, $im_url);
        $im_url = str_replace("[order_id]", $iid, $im_url);
        $im_url = str_replace("[unique_id]",$cs->gateway.'.'.$cs->gateway_id.'.'.$iid, $im_url);
        
        if($cs->published)
        {
            echo "<img src=\"{$im_url}\" wisth=1 height=1 border=0>";
        }
    }
    */
    
    include_once(dirname(__FILE__).'/view/history.php');
}

function jcsSaveRegistration() {

	global $database, $acl,$mainframe, $JCS_CONTINUE;
	global $mosConfig_sitename, $mosConfig_live_site, $mosConfig_useractivation;
	global $mosConfig_allowUserRegistration, $mosConfig_absolute_path;
	global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_fromname;
  
  $mosConfig_useractivation = 0;
	
  if ( $mosConfig_allowUserRegistration == 0 ) {
		mosNotAuth();
		return;
	}

	// simple spoof check security
	//josSpoofCheck();	
	
	$row = new mosUser( $database );

	if (!$row->bind( $_GET, 'usertype' )) {
		mosErrorAlert( $row->getError() );
	}

	mosMakeHtmlSafe($row);

	$row->id 		= 0;
	$row->usertype 	= '';
	$row->gid 		= $acl->get_group_id( 'Registered', 'ARO' );

	if ( $mosConfig_useractivation == 1 ) {
		$row->activation = md5( mosMakePassword() );
		$row->block = '1';
	}

	if (!$row->check()) {
		echo "<script> alert('".html_entity_decode($row->getError())."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	if(file_exists($mosConfig_absolute_path.'/administrator/components/com_securityimages/server.php'))
	{
		$securityimage_newpass_refid  = mosGetParam( $_REQUEST, 'securityimage_newpass_refid', '' );
		$securityimage_newpass_try    = mosGetParam( $_REQUEST, 'securityimage_newpass_try', '' );
		$securityimage_newpass_reload = mosGetParam( $_REQUEST, 'securityimage_newpass_reload', '' );         
		
		include_once ($mosConfig_absolute_path.'/administrator/components/com_securityimages/server.php');
		
		$checkSecurity = checkSecurityImage($securityimage_newpass_refid, $securityimage_newpass_try, $securityimage_newpass_reload);
	
		if (!$checkSecurity) {
			echo "<script> alert('Security Image do not match'); window.history.go(-1); </script>\n";
			exit();
		}
		
	}
	
	$pwd 				= $row->password;
	$row->password 		= md5( $row->password );
	$row->registerDate 	= date( 'Y-m-d H:i:s' );

	if (!$row->store()) {
		echo "<script> alert('".html_entity_decode($row->getError())."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();

	$name 		= $row->name;
	$email 		= $row->email;
	$username 	= $row->username;

	$subject 	= sprintf (_SEND_SUB, $name, $mosConfig_sitename);
	$subject 	= html_entity_decode($subject, ENT_QUOTES);
	
  $message = sprintf (JCS_ALERT_USER_REG, $name, $mosConfig_sitename, 
  $mosConfig_live_site."/index.php", $username, $pwd);

	$message = html_entity_decode($message, ENT_QUOTES);
	
	// check if Global Config `mailfrom` and `fromname` values exist
	if ($mosConfig_mailfrom != '' && $mosConfig_fromname != '') {
		$adminName2 	= $mosConfig_fromname;
		$adminEmail2 	= $mosConfig_mailfrom;
	} else {
	// use email address and name of first superadmin for use in email sent to user
		$query = "SELECT name, email"
		. "\n FROM #__users"
		. "\n WHERE LOWER( usertype ) = 'superadministrator'"
		. "\n OR LOWER( usertype ) = 'super administrator'"
		;
		$database->setQuery( $query );
		$rows = $database->loadObjectList();
		$row2 			= $rows[0];
		
		$adminName2 	= $row2->name;
		$adminEmail2 	= $row2->email;
	}

	// Send email to user
	mosMail($adminEmail2, $adminName2, $email, $subject, $message);

	// Send notification to all administrators
	$subject2 = sprintf (_SEND_SUB, $name, $mosConfig_sitename);
	$message2 = sprintf (_ASEND_MSG, $adminName2, $mosConfig_sitename, $row->name, $email, $username);
	$subject2 = html_entity_decode($subject2, ENT_QUOTES);
	$message2 = html_entity_decode($message2, ENT_QUOTES);

	// get email addresses of all admins and superadmins set to recieve system emails
	$query = "SELECT email, sendEmail"
	. "\n FROM #__users"
	. "\n WHERE ( gid = 24 OR gid = 25 )"
	. "\n AND sendEmail = 1"
	. "\n AND block = 0"
	;
	$database->setQuery( $query );
	$admins = $database->loadObjectList();
	
	foreach ( $admins as $admin ) {
		// send email to admin & super admin set to recieve system emails
		mosMail($adminEmail2, $adminName2, $admin->email, $subject2, $message2);
	}
  
  //$mainframe->login($username, $pwd, 1, $row->id);
  //$s = intval(mosGetParam( $_REQUEST, 'stype', false ));
  //$p = mosGetParam( $_REQUEST, 'payprocessor', false );
  mosRedirect("index.php?option=com_jcs&task=add", $JCS_CONTINUE);
}
?>
